package com.java1234.rocketmq;

import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import java.time.LocalDateTime;
import java.util.Random;

/**
 * @ClassName TransactionListenerImpl
 * @Description: TODO
 * @Author: Sunny
 * @Create: 2023-10-19 16:52
 * @Version 1.0
 **/
@RocketMQTransactionListener
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
// ... local transaction process, return bollback, commit or unknown
        System.out.println("我来查看事务executeLocalTransaction："+ LocalDateTime.now());
        //1.本地事务执行成功，生成消息索引（对消费者可见）
        //return RocketMQLocalTransactionState.COMMIT_MESSAGE;
        //2.本地事务执行失败，删除消息
        //return RocketMQLocalTransactionState.ROLLBACK_MESSAGE;
        //2.本地事务状态未知，待消息回查确认
        int num = new Random().nextInt(10);
        //int num = 6;
        if (num < 3) {
            return RocketMQLocalTransactionState.COMMIT;
        } else if (num < 6) {
            //本地事务执行失败，删除消息
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //等待本地事务check，即执行checkLocalTransaction()方法
        return RocketMQLocalTransactionState.UNKNOWN;
    }
    //事务回查  默认是60s，一分钟检查一次 默认是十五次也可以去自己配置
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
// ... check transaction status and return bollback, commit or unknown
        // 回查业务....
        //1.本地事务执行成功，生成消息索引（对消费者可见）
        //return LocalTransactionState.COMMIT_MESSAGE;
        //2.本地事务执行失败，删除消息
        //return LocalTransactionState.ROLLBACK_MESSAGE;
        //3.本地事务状态未知，待消息回查确认
        //return LocalTransactionState.UNKNOW;
        System.out.println("我来回查事务checkLocalTransaction："+ LocalDateTime.now());
        int num = new Random().nextInt(10);
        //int num = 6;
        if (num < 3) {
            //提交消息
            return RocketMQLocalTransactionState.COMMIT;
        } else if (num < 6) {
            //删除消息
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //等待本地事务check，即执行checkLocalTransaction()方法
        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
